<template>

  <div>
    <div class="fixed-card">
    <el-card>
    <el-page-header @back="goBack" content="个人中心">
    </el-page-header>
    </el-card>
    </div>
    <div class="content-container">
    <div class="PersonTop">
      <div class="PersonTop_img">
        <img :src="icon" />
      </div>
      <div class="PersonTop_text">
        <div class="user_text">
          <div class="user_name">
            <span> {{ realname }} </span>
          </div>
          <div class="user_qianming">
            <span> {{ readernumber }}</span>
          </div>
          <div>
            <el-button class="el-icon-lock" type="success" plain @click="dialogVisible = true">修改密码</el-button>
          </div>
        </div>
          <div style="padding: 40px;font-size: 30px; margin-left: -290px;">
        <span class="time" id="time" >
            <span class="date">{{ nowTime }}</span>
            <span class="hour" style="margin-left: 5px;">{{time.hour}}</span>
            <a class="split">:</a>
            <span class="minitus">{{time.minitus}}</span>
            <a class="split">:</a>
            <span class="seconds">{{time.seconds}}</span>
        </span>
          </div>
      </div>
    </div>
    <div class="person_body">
      <div class="person_body_left">
        <el-card class="box-card" :body-style="{ padding: '0px' }">
          <div slot="header" class="clearfix">
            <span class="person_body_list" style="border-bottom: none">个人中心</span>
          </div>
          <el-menu
              router
              active-text-color="#00c3ff"
              class="el-menu-vertical-demo"
              :default-active="this.def_url">
            <el-menu-item
                index="info"
                :route="{ name: 'info'}">
              <i class="el-icon-user"></i>
              <span slot="title">个人信息</span>
            </el-menu-item>
            <el-menu-item
                index="borrowing_record"
                :route="{ name: 'borrowing_record'}">
              <i class="el-icon-edit-outline"></i>
              <span slot="title">借阅记录</span>
            </el-menu-item>
            <el-menu-item
                index="book_collection"
                :route="{ name: 'book_collection'}">
              <i class="el-icon-collection"></i>
              <span slot="title">图书收藏</span>
            </el-menu-item>
            <el-menu-item
                index="read_books"
                :route="{ name: 'read_books'}">
              <i class="el-icon-notebook-2"></i>
              <span slot="title">已读图书</span>
            </el-menu-item>
            <el-menu-item
                index="my_posts"
                :route="{ name: 'my_posts'}">
              <i class="el-icon-edit"></i>
              <span slot="title">我的贴子</span>
            </el-menu-item>
            <el-menu-item
                index="my_comment"
                :route="{ name: 'my_comment'}">
              <i class="el-icon-chat-line-square"></i>
              <span slot="title">我的评论</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </div>
      <div class="person_body_right">
        <router-view></router-view>
      </div>
    </div>
  </div>
    <el-dialog
        title="修改密码"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
      <el-form :model="readerForm" ref="readerForm" :rules="rules" label-width="80px">
      <el-form-item label="旧密码" prop="password">
        <el-input v-model="readerForm.password"></el-input>
      </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="readerForm.newPassword"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmNewPassword">
          <el-input v-model="readerForm.confirmNewPassword"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancelDialog">取 消</el-button>
    <el-button type="primary" @click="updatePassword" plain>确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: "PersonalCenter",
  props: ["s"],
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.readerForm.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      time: {
        hour: "",
        minitus: "",
        seconds: ""
      },
      nowTime: "",
      week: [
        "星期天",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六"
      ],
      readerForm: {
        password: '',
        newPassword: '',
        confirmNewPassword: '',
      },
      dialogVisible: false,
      def_url: this.getInitialActiveMenu(),
      rules: {
        password: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
        ],
        confirmNewPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
      }
    };
  },
  mounted() {
    this.dateTime();
    this.def_url = this.getInitialActiveMenu();
  },
  methods: {
    dateTime() {
      this.timeFormate();
      setTimeout(() => {
        this.dateTime();
      }, 1000);
    },
    timeFormate() {
      const newtime = new Date();
      this.time.hour = this.getIncrease(newtime.getHours(), 2);
      this.time.minitus = this.getIncrease(newtime.getMinutes(), 2);
      this.time.seconds = this.getIncrease(newtime.getSeconds(), 2);
      this.nowTime =
          this.getIncrease(newtime.getFullYear(), 4) +
          "年" +
          this.getIncrease(newtime.getMonth() + 1, 2) +
          "月" +
          this.getIncrease(newtime.getDate(), 2) +
          "日 " +
          this.week[newtime.getDay()];
      //this.hour=
      // return `${this.time.hour}:${this.time.minitus}:${this.time.seconds}`;
    },
    getIncrease(num, digit) {
      var increase = "";
      for (var i = 0; i < digit; i++) {
        increase += "0";
      }
      return (increase + num).slice(-digit);
    },
    resetForm(){
      this.readerForm = {
        password: '',
        newPassword: '',
        confirmNewPassword: '',
      }
    },
    async updatePassword() {
      this.$refs.readerForm.validate(async (valid) => {
        if (valid) {
          try {
            // 验证旧密码
            const { data: oldPasswordRes } = await this.$axios.get("/reader/validateOldPassword", {
              params: {
                id: sessionStorage.getItem("id"),
                password: this.readerForm.password,
              },
            });
            if (oldPasswordRes.success) {
              // 旧密码正确，更新新密码
              const { data: res } = await this.$axios.put("/reader/updateReader", {
                id: sessionStorage.getItem("id"),
                password: this.readerForm.newPassword,
              });
              if (res.success) {
                this.$message.success("修改成功");
                this.dialogVisible = false;
                this.resetForm();
                this.logout()
              }
            } else {
              this.$message.error("旧密码错误，请重试");
            }
          } catch (error) {
            this.$message.error("修改失败，请重试");
          }
        } else {
          return false;
        }
      });
    },
    goBack() {
      this.$router.push({ name: 'front_page' });
    },
    logout(){
      window.localStorage.clear()
      window.sessionStorage.clear()
      this.$router.push('/login')
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.resetForm();
            this.$refs.readerForm.clearValidate();
            done();
          })
          .catch(_ => {});
    },
    cancelDialog() {
      this.dialogVisible = false;
      this.resetForm();
      this.$refs.readerForm.clearValidate();
    },
    getInitialActiveMenu() {
      const currentRouteName = this.$route.name;
      if (currentRouteName === 'info') return 'info';
      if (currentRouteName === 'borrowing_record') return 'borrowing_record';
      if (currentRouteName === 'book_collection') return 'book_collection';
      if (currentRouteName === 'read_books') return 'read_books';
      if (currentRouteName === 'my_comment') return 'my_comment';
      if (currentRouteName === 'my_posts') return 'my_posts';
      return 'info';
    }
  },
  watch: {
    '$route'(to) {
      // 监听路由变化，更新激活的菜单项
      this.def_url = to.name;
      sessionStorage.setItem('activeMenu', to.name);
    }
  },
  computed: {
    realname() {
      return sessionStorage.getItem("realname");
    },
    icon() {
      return sessionStorage.getItem("icon");
    },
    readernumber() {
      return sessionStorage.getItem("readernumber");
    },
}
}
</script>

<style scoped>
.txt-data .time {
  font-size: 1rem;
  margin-right: 0.5rem;
}
.split {
  animation: shark 1s step-end infinite;
  vertical-align: center;
  margin-left: 2px;
  margin-right: 2px;
}
@keyframes shark {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}
.me-video-player {
  background-color: transparent;
  width: 100%;
  height: 100%;
  object-fit: fill;
  display: block;
  position: fixed;
  left: 0;
  z-index: 0;
  top: 0;
}
.PersonTop {
  width: 1000px;
  height: 140px;
  padding-top: 20px;
  background-color: white;
  margin-top: 30px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  /*justify-content: center;*/
  /*align-items: center;*/
  border-radius: 5px;
}
.user_num {
  width: 40%;
  height: 100%;
  display: flex;
  align-items: center;
}

.user_num > div {
  text-align: center;
  border-right: 1px dotted #999;
  box-sizing: border-box;
  width: 80px;
  height: 40px;
  line-height: 20px;
}

.num_text {
  color: #999;
}
.PersonTop_img {
  width: 140px;
  height: 130px;
  background-color: #8c939d;
  margin-right: 24px;
  margin-left: 20px;
  overflow: hidden;
  border-radius: 50%;
}

.PersonTop_img img {
  width: 100%;
  height: 100%;
  border-radius: 20px;
}

.PersonTop_text {
  height: 120px;
  width: 880px;
  display: flex;
}

.user_text {
  width: 60%;
  height: 100%;
  line-height: 40px;
}

.user_name {
  font-weight: bold;
}
.user-v {
  margin-bottom: -5px;
}
.user-v-img {
  width: 15px;
  height: 15px;
}
.user-v-font {
  font-size: 15px;
  color: #00c3ff;
}
.user_qianming {
  font-size: 14px;
  color: #999;
}


.user_num > div {
  text-align: center;
  border-right: 1px dotted #999;
  box-sizing: border-box;
  width: 80px;
  height: 40px;
  line-height: 20px;
}




.el-menu-item>span {
  font-size: 16px;
  color: #999;
}

/*下面部分样式*/
.person_body {
  width: 1000px;
  margin-top: 210px;
  display: flex;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 5px;
}

.person_body_left {
  width: 27%;
  height: 600px;
  border-radius: 5px;
  margin-right: 3%;
  text-align: center;
}

.person_body_list {
  width: 100%;
  height: 50px;
  margin-top: 25px;
  font-size: 22px;
  border-bottom: 1px solid #f0f0f0;
  background-image: -webkit-linear-gradient(
      left,
      rgb(42, 134, 141),
      #e9e625dc 20%,
      #3498db 40%,
      #e74c3c 60%,
      #09ff009a 80%,
      rgba(82, 196, 204, 0.281) 100%
  );
  -webkit-text-fill-color: transparent;
  -webkit-background-clip: text;
  -webkit-background-size: 200% 100%;
  -webkit-animation: masked-animation 4s linear infinite;
}

.el-menu-item {
  margin-top: 22px;
}

.person_body_right {
  width: 70%;
  /* height: 500px; */
  border-radius: 5px;
  background-color: white;
}

.box-card {
  height: 552px;
}

/*ui样式*/
.el-button {
  width: 84px;
}
.txt-data .time {
  font-size: 1rem;
  margin-right: 0.5rem;
}
.split {
  animation: shark 1s step-end infinite;
  vertical-align: center;
  margin-left: 2px;
  margin-right: 2px;
}
@keyframes shark {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}
.fixed-card {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 1000; /* 确保卡片在其他内容之上 */
}
.content-container {
  margin-top: 50px; /* 根据卡片的高度调整 */
}
</style>